#ifndef STATE_CONFIG_MANAGER_H
#define STATE_CONFIG_MANAGER_H

#include <string>
#include <unordered_map>
#include <mutex>
#include <atomic>
#include "config.h"
#include <opencv2/opencv.hpp>
#include "rapidjson/document.h"
#include "rapidjson/filereadstream.h"
#include "msg_topic.h"
#include <sys/time.h>

// 状态与配置管理器类
class StateConfigManager {
public:
    // 禁止拷贝和赋值
    StateConfigManager(const StateConfigManager&) = delete; 
    StateConfigManager& operator=(const StateConfigManager&) = delete;
    void Init();
    // 获取单例实例

    static StateConfigManager& getInstance();

    // 更新状态
    void updateState(const std::string& key, const std::string& value);

    // 获取状态
    std::string getState(const std::string& key) const;

    // 加载配置
    void loadConfig(const std::string& configFilePath);




    void setAppData(int sensor, int status, float lower_heihgt);

    void getAppData1(int &outSensor, int &outStatus, float &outHeight) const;

    void setStatus(int status);
    void setSensor(int sensor);
    void setHeight(float height);

    int getStatus() const { return iStatus.load();};
    int getSensor() const { return iSensor.load();};
    float getHeight() const { return fHeight.load();};
    Config& getConfig(); 

    // camdarstatus
    long long getLocalMachineTime();
    long long getAiPreTime();
    long long getLiPreTime();
    void updateAiPreTime();
    void updateLiPreTime();
    bool sendStatus(int& res_sensor, int& res_stauts, int& res_ai_status, int& res_li_status, long long& res_ai_pre_time, long long& res_li_pre_time);

    bool getLogic();
    bool getSwitch();

private:
    StateConfigManager() = default; // 私有构造函数，确保外部无法直接创建实例

    mutable std::mutex mutex_; // 保护线程安全

    std::atomic<int> iStatus;
    std::atomic<int> iSensor;
    std::atomic<float> fHeight;
    bool bSwitch = false;
    bool bLogic = false;
    long long li_pre_time;
    long long ai_pre_time;
    Config config;

    std::string SAVE_APP_TXT = "/kdrm210_main/modules/camdar/config/app2camdar.txt";
    std::string json_config_path_ = "/kdrm210_main/modules/camdar/config/camdar_config.json";

    // app
    void readAppData();
    void getAppData(int &num1, float &num2);
    bool updateAppData(int sensor, float lower_altitude);
    void setSensor0(int status, int sensor, float lower_altitude);
    void setSensor2(int status, int sensor, float lower_altitude);



    // config
    void readDefaultConfig(const std::string& json_config_path);
    void parseCamIntTri(const rapidjson::Value& camIntTri, CamIntTri& cam_inttri);
    void parseDebugInfo(const rapidjson::Value& debugInfo, DebugInfo& debug_info);
    void parseCarConfig(const rapidjson::Value& carConfig, CarConfig& car_config);
    void parseTimeInterval(const rapidjson::Value& timeInterval, TimeInterval& time_interval);
    void parseSaveFlag(const rapidjson::Value& saveFlag, SaveFlag& save_flag);

    void printConfig() const;

};

#endif // STATE_CONFIG_MANAGER_H
